//
// Created by chaofengan on 23-8-29.
//

#include "process_using_table.h"
#include "algorithm"
#define IS_FREE -1
bool process_using_table::if_position_is_free(int position) {
    if(position_to_pid_table.count(position) == 0 or position_to_pid_table[position] == IS_FREE){
        return true;
    }
    return false;
}

void process_using_table::add_using(single_memory_using_record &a_log) {
    pid_t pid = a_log.pid;
    if(using_table.count(pid) == 0){
        std::vector<single_memory_using_record> tem_v;
        tem_v.push_back(a_log);
        using_table[pid] = tem_v;
    }else{
        using_table[pid].push_back(a_log);
    }

    if(position_to_pid_table.count(a_log.using_position) == 0 or position_to_pid_table[a_log.using_position] == IS_FREE){
        position_to_pid_table[a_log.using_position] = pid;
    }
}

void process_using_table::delete_using(pid_t pid, int position) {
    if(position_to_pid_table.count(pid) == 0){

    }else{
        position_to_pid_table[pid] = -1;
    }

    if(using_table.count(pid) == 0){

    }else{
        for(auto iter = using_table[pid].begin();iter!= using_table[pid].end();iter++){
            if(iter->using_position == position){
                using_table[pid].erase(iter);
                break;
            }
        }
    }
}
